package com.lagou.client.handler;

import com.lagou.invoke.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @author Kirito
 * @description:
 * @date 2020/05/26
 */
public class RpcClientHandler extends ChannelInboundHandlerAdapter implements Callable<String> {

    private ChannelHandlerContext context;

    private String result;

    private RpcRequest request;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.context = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        this.result = msg.toString();
        // 收到响应后唤醒等待的线程
        notify();
    }

    public synchronized String call() throws Exception {
        context.writeAndFlush(request);
        // 阻塞线程，等待响应结果
        wait();
        return result;
    }

    public void setRequest(RpcRequest request) {
        this.request = request;
    }
}
